<?php

namespace app\common\model\screen;

use fast\Random;
use fast\Rsa;
use think\Model;
use traits\model\SoftDelete;

class Share extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'screen_share';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'end_time_text'
    ];


    protected static function init()
    {
        parent::init(); // TODO: Change the autogenerated stub

        self::beforeInsert(function ($row) {
            do {
                $code = Random::alnum(6);
            } while(self::where('code', $code)->count());

            $row['code'] = $code;
            $row['share_token'] = md5($code);
        });
    }


    public function getStatusList()
    {
        return ['normal' => __('Status normal'), 'hidden' => __('Status hidden')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['end_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function page()
    {
        return $this->belongsTo('Page', 'page_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function excel()
    {
        return $this->belongsTo('Excel', 'excel_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
